package cn.itcast.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;

@Namespace("/")
@ParentPackage("struts-default")
@Controller
@Scope("prototype")
public class AreaAction extends ActionSupport implements ModelDriven<Area> {
	private static final long serialVersionUID = 1L;
	private Area area = new Area();
	@Autowired
	private AreaService areaService;

	@Override
	public Area getModel() {
		return area;
	}

	// 批量导入
	private File file;
	// private String fileFileName;

	public void setFile(File file) {
		this.file = file;
	}

	/*
	 * public void setFileFileName(String fileFileName) { this.fileFileName =
	 * fileFileName; }
	 */

	// 批量导入数据解析Excel
	@Action(value = "area_batchImport")
	public void batchImport() throws IOException {
		// 声明一个list集合用来存放area
		List<Area> areas = new ArrayList<Area>();
		// 加载.xls文件
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
		// 加载文件中的sheet
		HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
		// 读取sheet中的每一行数据
		for (Row row : hssfSheet) {
			// 跳过第一行数据,表头
			if (row.getRowNum() == 0) {
				continue;
			}
			// 跳过表中空行
			if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				continue;
			}
			// 封装Area
			Area area = new Area();
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince(row.getCell(1).getStringCellValue());
			area.setCity(row.getCell(2).getStringCellValue());
			area.setDistrict(row.getCell(3).getStringCellValue());
			area.setPostcode(row.getCell(4).getStringCellValue());
			// 基于pinyin4j生成城市编码和简码
			String province = area.getProvince();
			String city = area.getCity();
			String district = area.getDistrict();
			// 截取省市区的最后一个汉字
			province = province.substring(0, province.length() - 1);
			city = city.substring(0, city.length() - 1);
			district = district.substring(0, district.length() - 1);
			// 生成省市区简码
			String[] headArr = PinYin4jUtils.getHeadByString(province + city + district);
			StringBuilder sb = new StringBuilder();
			for (String head : headArr) {
				sb.append(head);
			}
			String shortcode = sb.toString();
			area.setShortcode(shortcode);
			// 生成编码
			String citycode = PinYin4jUtils.hanziToPinyin(city, "");
			area.setCitycode(citycode);
			// 将Area添加到list集合中
			areas.add(area);
		}
		areaService.addBatch(areas);
		hssfWorkbook.close();
	}

	// 带条件分页查询
	private Integer page;
	private Integer rows;

	public void setPage(Integer page) {
		this.page = page;
	}

	public void setRows(Integer rows) {
		this.rows = rows;
	}

	@Action(value = "area_pageQuery")
	public void pageQuery() throws IOException {
		// 构造分页对象
		Pageable pageable = new PageRequest(page - 1, rows);
		// 构造分页条件对象
		Specification<Area> specification = new Specification<Area>() {
			List<Predicate> list = new ArrayList<Predicate>();

			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				if (StringUtils.isNotBlank(area.getProvince())) {
					Predicate p1 = cb.like(root.get("province").as(String.class), "%" + area.getProvince() + "%");
					list.add(p1);
				}
				if (StringUtils.isNotBlank(area.getCity())) {
					Predicate p2 = cb.like(root.get("city").as(String.class), "%" + area.getCity() + "%");
					list.add(p2);
				}
				if (StringUtils.isNotBlank(area.getDistrict())) {
					Predicate p3 = cb.like(root.get("district").as(String.class), "%" + area.getDistrict() + "%");
					list.add(p3);
				}
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		Page<Area> pageData = areaService.pageQuery(specification, pageable);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", pageData.getTotalElements());
		map.put("rows", pageData.getContent());
		String jsonString = JSONArray.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect);
		ServletActionContext.getResponse().setContentType("application/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().write(jsonString);
	}

	// 添加或者修改
	@Action(value = "area_add", results = {
			@Result(name = "success", location = "./pages/base/area.html", type = "redirect") })
	public String add() {
		String province = area.getProvince();
		String city = area.getCity();
		String district = area.getDistrict();
		if ("".equals(area.getShortcode())) {
			// 基于pinyin4j生成城市编码和简码
			// 截取省市区的最后一个汉字
			province = province.substring(0, province.length() - 1);
			city = city.substring(0, city.length() - 1);
			district = district.substring(0, district.length() - 1);
			// 生成省市区简码
			String[] headArr = PinYin4jUtils.getHeadByString(province + city + district);
			StringBuilder sb = new StringBuilder();
			for (String head : headArr) {
				sb.append(head);
			}
			String shortcode = sb.toString();
			area.setShortcode(shortcode);
		}
		if ("".equals(area.getCitycode())) {
			// 生成编码
			String citycode = PinYin4jUtils.hanziToPinyin(city, "");
			area.setCitycode(citycode);
		}
		areaService.add(area);
		return SUCCESS;
	}

	// 删除
	private String idsStr;

	public void setIdsStr(String idsStr) {
		this.idsStr = idsStr;
	}

	@Action(value = "area_del", results = {
			@Result(name = "success", location = "./pages/base/area.html", type = "redirect") })
	public String del() {
		areaService.del(idsStr);
		return SUCCESS;
	}

	// 查找所有
	@Action(value = "area_findAll")
	public void findAll() throws IOException {
		List<Area> list = areaService.findAll();
		String jsonString = JSONArray.toJSONString(list, SerializerFeature.DisableCircularReferenceDetect);
		ServletActionContext.getResponse().setContentType("application/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().write(jsonString);
	}
}
